package mailsystem;

import java.util.ArrayList;

import mailsystem.persistance.MailsystemPersistance;


/**
 * A system of voice mail boxes.
 */
public class MailSystem {	

	/**
	 * Constructs a mail system with a given number of mailboxes
	 * 
	 * @throws Exception 
	 */
	public MailSystem(MailsystemPersistance repo) {
		repository = repo;
		mailboxes = new ArrayList<Mailbox>(repository.listAllMailbox());
		
		for ( int i = 0; i < mailboxes.size(); i++)
			mailboxes.get(i).loadContacts(mailboxes);
	}

	/**
	 * Locate a mailbox.
	 * 
	 * @param ext
	 *            the extension number
	 * @return the mailbox or null if not found
	 */
	public Mailbox findMailbox(String ext) {
		try {
			int i = Integer.parseInt(ext);

			if (1 <= i && i <= mailboxes.size())
				return mailboxes.get(i - 1);
			else
				return null;
		} catch (NumberFormatException numberFormatException) {
			return null;
		}
	}	

	private ArrayList<Mailbox> mailboxes;
	private MailsystemPersistance repository;
}
